/**
 * Created by yangchen on 2018/5/30
 * */

let oneClickRepeatRequestCount = 3; // 重复请求次数  刷新页面会重置
/**
 * 调用openWeb接口做数据转化
 * @param data
 */

const transformDataByOpenWebFetch = (data) => {
  return new Promise((resolve, reject) => {
    let token = data.saasData.data.token;
    let openWebTaxApiUrl = 'https://open.cs.zbj.com/oapi/tax/convert';
    // let openWebTaxApiUrl = 'https://open.cs.test.zbjdev.com/oapi/tax/convert';
    let openWebParams = data.saasData.data.openParams;
    openWebParams.isZip = openWebParams.isZip === 'true';
    openWebParams.inputData.isYearReport = openWebParams.inputData.isYearReport === 'true';
    const isJson = openWebParams.outPutType === 'json';
    const isXml = openWebParams.outPutType === 'xml';
    const isJsonRes = (isXml && !openWebParams.isZip) || isJson;
    let inputData = openWebParams.inputData;
    if (inputData.sheetType === 'sds') {
      inputData.sheetType = 'profit';
    }

    let headers = {
      Authorization: `${token.token_type} ${token.access_token}`,
      'Content-Type': 'application/json'
    };
    let body;
    if (JSON.stringify) {
      body = JSON.stringify(openWebParams);
    } else {
      body = json2str(openWebParams);
    }
    fetch(openWebTaxApiUrl, {
      method: 'POST',
      body,
      headers: headers,
      mode: 'cors'
    }).then(res => {
      if (isJsonRes) {
        return res.json();
      }
      return res.blob();
    }).then(res => {
      if (res && !isJson) { // 文件
        data.saasData.data = {
          type: 'file',
          data: res
        };
        resolve(data);
      } else if (res.success && isJson) {
        data.saasData.data = res.data;
        resolve(data);
      } else {
        if (--oneClickRepeatRequestCount > 0) {
          window.postMessage({
            event: 'getSaasDataAgain'
          }, '*');
        }
        console.error('openWeb数据转换失败');
      }
    }).catch(e => {
      console.error(e);
    });
  });
};

function json2str(o) {
  let arr = [];
  const fmt = function(s) {
    if (typeof s === 'object' && s !== null) return json2str(s);
    return /^(string)$/.test(typeof s) ? `"${s}"` : s;
  };
  let keys = Object.keys(o);
  arr = keys.map(key => {
    return `"${key}":${fmt(o[key])}`;
  });
  return `{${arr.join(',')}}`;
}

function deepCopy(obj) {
  var result = Array.isArray(obj) ? [] : {};
  for (let key in obj) {
    // eslint-disable-next-line no-prototype-builtins
    if (obj.hasOwnProperty(key)) {
      if (typeof obj[key] === 'object' && obj[key] !== null) {
        result[key] = deepCopy(obj[key]); // 递归复制
      } else {
        result[key] = obj[key];
      }
    }
  }
  return result;
}

/**
 * 转换数据
 * @param saasData
 * @param baseInfo
 * @returns {Promise.<*>}
 */
const transformDataByOpenWeb = async ({ saasData, baseInfo }) => {
  let saasDataParams;
  if (JSON.stringify) {
    saasDataParams = JSON.parse(JSON.stringify(saasData));
  } else {
    saasDataParams = deepCopy(saasData);
  }


  let data = await transformDataByOpenWebFetch({ saasData, baseInfo });
  if (saasDataParams.isYearReport) { // 如果是年报 同时需要转换上年数据
    saasDataParams.data.openParams.inputData.data = saasDataParams.data.openParams.inputData.lastYearData;
    const lastYearData = await transformDataByOpenWebFetch({ saasData: saasDataParams, baseInfo });
    data.saasData.lastYearData = lastYearData.saasData.data;
  }
  return data;
};

export {
  transformDataByOpenWeb
};
